package controller

import (
	"booksPro/dao"
	"booksPro/model"
	"booksPro/utils"
	"net/http"
	"text/template"
	"time"
)

func ToPay(w http.ResponseWriter, r *http.Request) {
	session, _ := dao.IsLogin(r)
	useID := session.UserID
	//获取购物车
	cart, _ := dao.GetCartByUserID(useID)
	//生成订单id
	orderID := utils.CreateUUID()
	//创建order对象
	order := &model.Order{
		OrderID:     orderID,
		CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
		TotalCount:  cart.TotalCount,
		TotalAmount: cart.TotalAmount,
		State:       0,
		UserID:      int64(cart.UserID),
	}
	//保存订单order到数据库
	dao.AddOrder(order)
	//创建订单项 并保存数据库
	for _, cartItem := range cart.CartItems {
		orderItem := &model.OrderItem{
			Count:   cartItem.Count,
			Amount:  cartItem.Amount,
			ImgPath: cartItem.Book.ImgPath,
			Title:   cartItem.Book.Title,
			Author:  cartItem.Book.Author,
			Price:   cartItem.Book.Price,
			OrderID: orderID,
		}
		//插入到订单项到表中
		dao.AddOrderItem(orderItem)
		//更新图书表 中 库存和销量
		book := cartItem.Book
		book.Sales = book.Sales + int(cartItem.Count)
		book.Stock = book.Stock - int(cartItem.Count)
		dao.UpdateBook(book)
	}
	//清除购物车
	dao.DeleteCartByCartID(cart.CartID)
	dao.DeleteCartItemsByCartID(cart.CartID)
	t := template.Must(template.ParseFiles("views/pages/cart/checkout.html"))
	session.OrderID = orderID
	t.Execute(w, session)
}

func GetOrders(w http.ResponseWriter, r *http.Request) {
	orders, _ := dao.GetOrders()
	t := template.Must(template.ParseFiles("views/pages/order/order_manager.html"))
	t.Execute(w, orders)

}

func GetMyOrder(w http.ResponseWriter, r *http.Request) {
	session, _ := dao.IsLogin(r)
	orders, _ := dao.GetOrderByUserId(session.UserID)
	session.Orders = orders
	t := template.Must(template.ParseFiles("views/pages/order/order.html"))
	t.Execute(w, session)
}

func GetOrderInfo(w http.ResponseWriter, r *http.Request) {
	orderID := r.FormValue("orderId")
	orders, _ := dao.GetOrderItemsByOrderID(orderID)
	t := template.Must(template.ParseFiles("views/pages/order/order_info.html"))
	t.Execute(w, orders)
}

func SendOrder(w http.ResponseWriter, r *http.Request) {
	orderID := r.FormValue("orderId")
	dao.UpdateOrderState(orderID, 1)
	GetOrders(w, r)
}

func TakeOrder(w http.ResponseWriter, r *http.Request) {
	orderID := r.FormValue("orderId")
	dao.UpdateOrderState(orderID, 2)
	GetMyOrder(w, r)
}
